<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二进制音频流播放</title>
</head>
<body>
<h1>二进制音频流播放</h1>
<audio id="audio" controls></audio>
<input id="input" ></input>
<button id="play">播放</button>

<script >
    // 音频流的 URL
    const audioStreamUrl = "http://127.0.0.1:8080/audio-tts?message=";

    // 获取 DOM 元素
    const audioElement = document.getElementById("audio");
    const playButton = document.getElementById("play");
    const input = document.getElementById("input");


    // 获取二进制音频流并播放
    async function fetchAndPlayAudio() {
        try {
            // 使用 Fetch API 获取音频流
            const response = await fetch(audioStreamUrl+input.value);
            if (!response.ok) {
                throw new Error("网络请求失败");
            }

            // 将响应数据转换为 ArrayBuffer
            const arrayBuffer = await response.arrayBuffer();
            console.log("arrayBuffer",arrayBuffer)

            // 将 ArrayBuffer 转换为 Blob
            const blob = new Blob([arrayBuffer], { type: "audio/mp3" });

            // 创建 Blob URL 并绑定到 audio 元素
            const blobUrl = URL.createObjectURL(blob);
            audioElement.src = blobUrl;

            console.log("音频已加载，点击播放按钮开始播放");
        } catch (error) {
            console.error("加载音频失败:", error);
        }

        audioElement.play();
        console.log("开始播放音频");
    }

    // 点击播放按钮
    playButton.addEventListener("click", () => {
        console.log(input)
        console.log(input.value)
        // 初始化加载音频
        fetchAndPlayAudio();
    });

</script>
</body>
</html>